import React, { useEffect, useState } from 'react';
import axios from '../axios';
import userStore from '../stores/UserStore'; // 假设 UserStore 文件路径正确
import './PersonalInfo.css';

const PersonalInfo = () => {
  const [userData, setUserData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    // 从 userStore 获取用户ID
    const user = userStore.getUser();
    const userId = user?.id; 

    // 调用后端接口获取用户信息
    axios.post('/users/personalcenter/info', { id: userId }) // 使用POST请求并传递用户ID
      .then(response => {
        if (response.data.code === 2000) {
          setUserData(response.data.data); // 后端返回的数据结构是 { code, msg, data }
        } else {
          setError(response.data.msg);
        }
        setLoading(false);
      })
      .catch(error => {
        console.error('Error fetching user data:', error);
        setError('加载用户信息失败');
        setLoading(false);
      });
  }, []);

  if (loading) {
    return <div>加载中...</div>;
  }

  if (error) {
    return <div>{error}</div>;
  }

  return (
    <div className="user-info">
      <h2>个人信息</h2>
      <div className="info-item">
        <span className="label">用户名：</span>
        <span className="value">{userData?.username || '未设置'}</span>
      </div>
      <div className="info-item">
        <span className="label">性别：</span>
        <span className="value">{userData?.gender || '未设置'}</span>
      </div>
      <div className="info-item">
        <span className="label">账号：</span>
        <span className="value">{userData?.account || '未设置'}</span>
      </div>
      <div className="info-item">
        <span className="label">电话：</span>
        <span className="value">{userData?.phone || '未设置'}</span>
      </div>
      <div className="info-item">
        <span className="label">生日：</span>
        <span className="value">{userData?.birthday || '未设置'}</span>
      </div>
    </div>
  );
};

export default PersonalInfo;